package com.atguigu.crowd.handler;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.api.RedisRemoteService;
import com.atguigu.crowd.config.ShortMessageProperties;
import com.atguigu.crowd.constant.CrowdContant;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.entity.vo.MemberVO;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
public class MemberHandler {

    @Autowired
    private ShortMessageProperties messageProperties;

    @Autowired
    private RedisRemoteService redisRemoteService;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    @RequestMapping("/auth/member/logout")
    public String logout(HttpSession session){
        session.invalidate();

        return "redirect:/";
    }
    @RequestMapping("/auth/member/do/login")
    public String login(@RequestParam("loginacct") String loginacct,
                        @RequestParam("userpswd") String userpswd,
                        ModelMap modelMap,
                        HttpSession session
                    ){

        ResultEntity<MemberPO> memberPOResultEntity = mySQLRemoteService.getMemberPOByLoginAcctRemote(loginacct);

        if (ResultEntity.FAILED.equals(memberPOResultEntity.getResult())){
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,memberPOResultEntity.getMessage());

            return "member-login";
        }
        MemberPO memberPO = memberPOResultEntity.getData();
        if (memberPO==null){
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,CrowdContant.MESSAGE_LOGIN_FAILED);

            return "member-login";
        }
        //比较密码
        String userDataBase = memberPO.getUserpswd();

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        boolean matches = passwordEncoder.matches(userpswd,userDataBase);

        System.out.println(matches);
        if (!matches){
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,CrowdContant.MESSAGE_LOGIN_FAILED);

            return "member-login";
        }

        //密码一致
        MemberLoginVO memberLoginVO = new MemberLoginVO(memberPO.getId(), memberPO.getUsername(), memberPO.getEmail());

        session.setAttribute(CrowdContant.ATTR_NAME_MEMBER,memberLoginVO);




        return "redirect:http://localhost:80/auth/to/member/center/page";
    }
    @RequestMapping("/auth/do/member/register")
    public String register(MemberVO memberVO, ModelMap modelMap){
        //获取手机号
        String phoneNum = memberVO.getPhoneNum();

        //拼接存在redis验证码的key
        String key=CrowdContant.REDIS_CODE_MESSAGE+phoneNum;

        //从redis中查询验证码，
        ResultEntity<String> resultEntity = redisRemoteService.getRedisStringValueByKeyRemote(key);
        // 检查查询是否有效

        String result=resultEntity.getResult();
        if(ResultEntity.FAILED.equals(result)){
            modelMap.addAttribute(CrowdContant.ATTR_MAME_MESSAGE,resultEntity.getMessage());

            return "redirect:/auth/to/member-reg.html";
        }
        if(ResultEntity.SUCCESS.equals(result)){
            //比较验证码是否一致
            String redisCode = resultEntity.getData();

            if (redisCode!=null){
                String fromCode = memberVO.getCode();
                if (Objects.equals(redisCode,fromCode)){
                    //验证码一致，删除redis中的验证码
                    redisRemoteService.removeRedisKeyRemote(key);

                    //执行密码加密
                    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                    String userpswd = memberVO.getUserpswd();
                    String encode = passwordEncoder.encode(userpswd);
                    memberVO.setUserpswd(encode);

                    //执行保存
                    MemberPO memberPO = new MemberPO();

                    //复制属性
                    BeanUtils.copyProperties(memberVO,memberPO);

                    //调用远程保存方法

                }
            }

        }


        return "redirect:http://localhost:80/auth/to/member/login/page";
    }
    @RequestMapping("/auth/member/send/short/message.json")
    public ResultEntity<String> sendMessage(@RequestParam("phoneNum") String phoneNum){

        String appcode = messageProperties.getAppcode();

        String host = messageProperties.getHost();

        String method = messageProperties.getMethod();

        String path = messageProperties.getPath();

        String sign = messageProperties.getSign();

        String skin = messageProperties.getSkin();
        //发送验证码到phoneNum手机
        ResultEntity<String> sendMessageResultEntity = CrowdUtil.sendShortMessage(host, path, method, phoneNum, appcode, sign, skin);


        //判断短信是否发送成功
        if(ResultEntity.SUCCESS.equals(sendMessageResultEntity.getResult())){
            //如果成功则将验证码存入redis
            String key= CrowdContant.REDIS_CODE_MESSAGE+phoneNum;

            String code=sendMessageResultEntity.getData();

            ResultEntity<String> saveresultEntity = redisRemoteService.setRedisKeyValueRemoteWithTimeOut(key, code, 5, TimeUnit.MINUTES);

            if (ResultEntity.SUCCESS.equals(saveresultEntity.getResult())){
                return ResultEntity.successWithoutData();
            }else {
                return saveresultEntity;
            }


        }else {
            return sendMessageResultEntity;
        }

    }
    }
